package com.pray.praymall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pray.common.enume.OrderStatusEnum;
import com.pray.common.to.SkuHasStockTo;
import com.pray.common.to.mq.OrderTo;
import com.pray.common.utils.PageUtils;
import com.pray.common.utils.Query;
import com.pray.common.utils.R;
import com.pray.common.vo.MemberResponseVo;
import com.pray.praymall.order.constant.OrderConstant;
import com.pray.praymall.order.dao.OrderDao;
import com.pray.praymall.order.entity.OrderEntity;
import com.pray.praymall.order.entity.OrderItemEntity;
import com.pray.praymall.order.entity.PaymentInfoEntity;
import com.pray.praymall.order.feign.CartFeignService;
import com.pray.praymall.order.feign.MemberFeignService;
import com.pray.praymall.order.feign.ProductFeignService;
import com.pray.praymall.order.feign.WmsFeignService;
import com.pray.praymall.order.interceptor.LoginUserInterceptor;
import com.pray.praymall.order.service.OrderItemService;
import com.pray.praymall.order.service.OrderService;
import com.pray.praymall.order.service.PaymentInfoService;
import com.pray.praymall.order.to.OrderCreateTo;
import com.pray.praymall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private final ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private WmsFeignService wmsFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private ThreadPoolExecutor pool;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        MemberResponseVo loginUser = LoginUserInterceptor.loginUser.get();
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();

        // *********拿到浏览器发过来的请求数据**********
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 1、远程查询所有的收货地址
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            // *********每个异步线程需要共享请求，否则异步任务会丢失请求**********
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(loginUser.getId());
            orderConfirmVo.setAddress(address);
        }, pool);
        // 2、远程查询所有选中的购物项
        CompletableFuture<Void> getItemsFuture = CompletableFuture.runAsync(() -> {
            // *********每个异步线程需要共享请求，否则异步任务会丢失请求**********
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> cartItems = cartFeignService.getCurrentUserCartItems();
            orderConfirmVo.setItems(cartItems);
        }, pool).thenRunAsync(() -> {
            // *********每个异步线程需要共享请求，否则异步任务会丢失请求**********
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> skuIds = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R r = wmsFeignService.getSkusHasStock(skuIds);
            if (r.getCode() == 0) {
                List<SkuHasStockTo> vos = r.getData(new TypeReference<List<SkuHasStockTo>>() {
                });
                if (vos != null && vos.size() > 0) {
                    Map<Long, Boolean> map = vos.stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
                    orderConfirmVo.setStocks(map);
                }
            }
        }, pool);


        // 3、用户积分
        orderConfirmVo.setIntegration(loginUser.getIntegration());
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginUser.getId(), token, 30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);

        CompletableFuture.allOf(getAddressFuture, getItemsFuture).get();
        return orderConfirmVo;
    }

//    @GlobalTransactional
    @Transactional
    @Override
    public OrderSubmitResponseVo submitOrder(OrderSubmitVo vo) {
        OrderSubmitResponseVo responseVo = new OrderSubmitResponseVo();
        orderSubmitVoThreadLocal.set(vo);
        MemberResponseVo loginUser = LoginUserInterceptor.loginUser.get();
        // 下单：去创建订单，验令牌，验价格，锁库存
        // 1、验令牌【令牌的对比和删除必须保证原子性】
        // 0:令牌失败，1：对比令牌成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class),
                Collections.singletonList(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginUser.getId()), orderToken);
        if (result.equals(0L)) {
            // 令牌验证失败
            responseVo.setCode(1);
        } else {
            // 令牌验证成功
            // 1、创建订单，订单项等信息
            OrderCreateTo order = createOrder();
            // 2、验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();

            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                // 误差范围小于0.01就认为是验价成功的
                // 3、保存订单
                saveOrder(order);

                // 4、库存锁定
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(locks);
                R r = wmsFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    // 锁定成功
                    responseVo.setOrder(order.getOrder());
                    // 发送消息
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                } else {
                    // 锁定失败
                    responseVo.setCode(3);
                }
            } else {
                responseVo.setCode(2);
            }
        }
        return responseVo;
        /*String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginUser.getId());
        if (orderToken != null && orderToken.equals(redisToken)) {
            // 令牌验证通过
        } else {

        }*/
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        // 查询这个订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if (OrderStatusEnum.CREATE_NEW.getCode().equals(orderEntity.getStatus())) {
            // 未付款的状态才需要关单（取消订单）
            OrderEntity order = new OrderEntity();
            order.setId(orderEntity.getId());
            order.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(order);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);
            // 发送给mq
            try {
                // TODO 保证消息一定要发出去，每一个消息都做好日志记录（给数据库保存每一个消息的详细信息）
                // TODO 定期扫描数据库将失败的消息再发送一遍
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            } catch (Exception e) {
                // TODO 将没发送成功的消息进行重试发送
            }
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        BigDecimal totalAmount = order.getTotalAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(totalAmount.toString());
        payVo.setOut_trade_no(order.getOrderSn());
        List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        if (itemEntities != null && itemEntities.size() > 0) {
            payVo.setSubject(itemEntities.get(0).getSkuName());
            payVo.setBody(itemEntities.get(0).getSkuAttrsVals());
        }
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberResponseVo member = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
                        .eq("member_id", member.getId())
                        .orderByDesc("id")
        );
        List<OrderEntity> entities = page.getRecords().stream().peek(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
        }).collect(Collectors.toList());

        page.setRecords(entities);
        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo vo) {
        String orderSn = vo.getOut_trade_no();
        // 1、保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        // 支付宝交易流水号
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        // 订单号
        infoEntity.setOrderSn(orderSn);
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(infoEntity);

        // 2、修改订单的状态信息
        if ("TRADE_SUCCESS".equals(vo.getTrade_status()) || "TRADE_FINISHED".equals(vo.getTrade_status())) {
            // 支付成功
            baseMapper.updateOrderStatus(orderSn, OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    /**
     * 保存订单数据
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        // 1、生成订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity entity = buildOrder(orderSn);
        // 2、获取到所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);

        // 3、计算价格相关

        computePrice(entity, itemEntities);
        orderCreateTo.setOrder(entity);
        orderCreateTo.setOrderItems(itemEntities);
        return orderCreateTo;
    }

    private void computePrice(OrderEntity entity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.00");
        BigDecimal promotionAmountTotal = new BigDecimal("0.00");
        BigDecimal couponAmountTotal = new BigDecimal("0.00");
        BigDecimal integrationAmountTotal = new BigDecimal("0.00");

        Integer giftGrowth = 0;
        Integer integralTotal = 0;

        // 订单的总额，叠加每一个订单项的总额信息
        for (OrderItemEntity itemEntity : itemEntities) {
            total = total.add(itemEntity.getRealAmount());
            promotionAmountTotal = promotionAmountTotal.add(itemEntity.getPromotionAmount());
            couponAmountTotal = couponAmountTotal.add(itemEntity.getCouponAmount());
            integrationAmountTotal = integrationAmountTotal.add(itemEntity.getIntegrationAmount());
            giftGrowth += itemEntity.getGiftGrowth();
            integralTotal += itemEntity.getGiftIntegration();
        }
        // 1、订单价格相关
        entity.setTotalAmount(total);
        // 应付总额
        entity.setPayAmount(total.add(entity.getFreightAmount()));
        entity.setPromotionAmount(promotionAmountTotal);
        entity.setCouponAmount(couponAmountTotal);
        entity.setIntegrationAmount(integrationAmountTotal);

        // 设置积分和成长值
        entity.setGrowth(giftGrowth);
        entity.setIntegration(integralTotal);
    }

    private OrderEntity buildOrder(String orderSn) {
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(memberResponseVo.getId());
        entity.setMemberUsername(memberResponseVo.getUsername());
        // 2、获取收货地址信息
        OrderSubmitVo submitVo = orderSubmitVoThreadLocal.get();
        R fare = wmsFeignService.getFare(submitVo.getAddrId());
        if (fare.getCode() == 0) {
            FareVo fareResponse = fare.getData(new TypeReference<FareVo>() {
            });
            // 设置运费信息
            entity.setFreightAmount(fareResponse.getFare());
            // 设置收货人信息
            entity.setReceiverName(fareResponse.getAddress().getName());
            entity.setReceiverPhone(fareResponse.getAddress().getPhone());
            entity.setReceiverPostCode(fareResponse.getAddress().getPostCode());
            entity.setReceiverProvince(fareResponse.getAddress().getProvince());
            entity.setReceiverCity(fareResponse.getAddress().getCity());
            entity.setReceiverRegion(fareResponse.getAddress().getRegion());
            entity.setReceiverDetailAddress(fareResponse.getAddress().getDetailAddress());
        }
        // 设置订单的状态
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        // 默认未删除
        entity.setDeleteStatus(0);
        return entity;
    }


    /**
     * 构建所有订单项数据
     *
     * @param orderSn 订单号
     * @return 订单项集合
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        List<OrderItemEntity> itemEntities = null;
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            itemEntities = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
        }
        return itemEntities;
    }

    /**
     * 构建某一个订单项
     *
     * @param cartItem 购物车项
     * @return 订单项
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        // 1、订单信息：订单号
        OrderItemEntity itemEntity = new OrderItemEntity();
        // 2、商品的spu信息
        R r = productFeignService.getSpuInfoBySkuId(cartItem.getSkuId());
        if (r.getCode() == 0) {
            SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
            });
            itemEntity.setSpuId(data.getId());
            itemEntity.setSpuName(data.getSpuName());
            itemEntity.setSpuBrand(data.getBrandId().toString());
            itemEntity.setCategoryId(data.getCatalogId());
        }
        // 3、商品的sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSpuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        // 4、优惠信息【不做】
        // 5、积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());

        // 6、订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0.00"));
        itemEntity.setCouponAmount(new BigDecimal("0.00"));
        itemEntity.setIntegrationAmount(new BigDecimal("0.00"));
        BigDecimal skuPrice = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity()));
        BigDecimal realPrice = skuPrice.subtract(itemEntity.getPromotionAmount()).subtract(itemEntity.getCouponAmount()).subtract(itemEntity.getIntegrationAmount());
        // 当前订单项的实际金额：商品总额减去各种优惠
        itemEntity.setRealAmount(realPrice);
        return itemEntity;
    }

}